import Taro from '@tarojs/taro'
import { getBaseUrl, normalToast } from '@/utils/utils'

const interceptor = function (chain) {
  const requestParams = chain.requestParams
  const token = Taro.getStorageSync('token') || ''
  const tokenHeader = {}
  if (token) {
    Object.assign(tokenHeader, {
      ['token']: token,
    })
  }
  const params = {
    url: BASE_URL + requestParams.url,
    timeout: 3000,
    header: {
      ...requestParams.header,
      ...tokenHeader,
    },
  }

  const requestConfig = {
    ...requestParams,
    ...params,
  }

  return chain
    .proceed(requestConfig)
    .then((response) => {
      return response
    })
    .catch((error) => {
      console.log('ddd---', error)
      const title = error.response?.data?.errmsg || error.errmsg || ERROR_MESSAGE
      normalToast(title)
      return Promise.reject(error)
    })
}

Taro.addInterceptor(interceptor)

export default {
  request: Taro.request,
}
